package com.aigestudio.wheelpicker.widgets;

import static com.aigestudio.wheelpicker.util.Constants.FLOAT_1_5;
import static com.aigestudio.wheelpicker.util.Constants.INT_1;
import static com.aigestudio.wheelpicker.util.Constants.INT_2;
import static com.aigestudio.wheelpicker.util.Constants.INT_5;

import com.aigestudio.wheelpicker.WheelPicker;
import com.aigestudio.wheelpicker.model.City;
import com.aigestudio.wheelpicker.model.Province;
import com.aigestudio.wheelpicker.util.LogUtil;

import ohos.agp.components.AttrHelper;
import ohos.agp.components.AttrSet;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.app.Context;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * WheelAreaPicker
 * Created by Administrator on 2016/9/14 0014.
 */
public class WheelAreaPicker extends DirectionalLayout implements IWheelAreaPicker {
    private static final String TAG = WheelAreaPicker.class.getSimpleName() + " test_wheel";

    private static final float ITEM_TEXT_SIZE = 18;

    private static final String SELECTED_ITEM_COLOR = "#353535";

    private static final String RAW_FILE_PATH = "resources/rawfile/";

    private static final int PROVINCE_INITIAL_INDEX = 0;

    private Context mContext;

    private List<Province> mProvinceList;

    private List<City> mCityList;

    private List<String> mProvinceNames;

    private List<String> mCityNames;

    private LayoutConfig mLayoutConfig;

    private WheelPicker mWheelPickerProvince;

    private WheelPicker mWheelPickerCity;

    private WheelPicker mWheelPickerArea;

    public WheelAreaPicker(Context context) {
        this(context, null);
    }

    public WheelAreaPicker(Context context, AttrSet attrSet) {
        super(context, attrSet);
        mContext = context;
        initLayoutParams();
        initView(context);
        try {
            mProvinceList = getJsonDataFromAssets(mContext);
        } catch (IOException e) {
            LogUtil.error(TAG, "loadRegionsFromFile : IOException");
        }
        obtainProvinceData();
        addListenerToWheelPicker();
    }

    private static List<Province> getJsonDataFromAssets(Context context) throws IOException {
        ObjectInputStream objectInputStream = null;
        List<Province> provinceList = null;

        String path = RAW_FILE_PATH + "RegionJsonData.dat";
        try (InputStream inputStream = context.getResourceManager().getRawFileEntry(path).openRawFile()) {
            objectInputStream = new ObjectInputStream(inputStream);
            provinceList = (List<Province>) objectInputStream.readObject();

        } catch (FileNotFoundException exception) {
            LogUtil.error(TAG, "loadRegionsFromFile : FileNotFoundException");
        } catch (IOException exception) {
            LogUtil.error(TAG, "loadRegionsFromFile : IOException");
        } catch (ClassNotFoundException e) {
            LogUtil.error(TAG, "loadRegionsFromFile : ClassNotFoundException");
        } finally {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
        }
        return provinceList;
    }

    private void initLayoutParams() {
        mLayoutConfig = new LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,
            ComponentContainer.LayoutConfig.MATCH_CONTENT);
        mLayoutConfig.setMargins(INT_5, INT_5, INT_5, INT_5);
        mLayoutConfig.width = 0;
    }

    private void initView(Context context) {
        setOrientation(HORIZONTAL);
        mProvinceNames = new ArrayList<>();
        mCityNames = new ArrayList<>();
        mWheelPickerProvince = new WheelPicker(mContext);
        mWheelPickerCity = new WheelPicker(context);
        mWheelPickerArea = new WheelPicker(context);
        initWheelPicker(mWheelPickerProvince, INT_1);
        initWheelPicker(mWheelPickerCity, FLOAT_1_5);
        initWheelPicker(mWheelPickerArea, FLOAT_1_5);
    }

    private void initWheelPicker(WheelPicker wheelPicker, float weight) {
        mLayoutConfig.weight = weight;
        wheelPicker.setItemTextSize(dip2px(mContext, ITEM_TEXT_SIZE));
        wheelPicker.setSelectedItemTextColor(AttrHelper.convertValueToColor(SELECTED_ITEM_COLOR).getValue());
        wheelPicker.setCurved(true);
        wheelPicker.setLayoutConfig(mLayoutConfig);
        addComponent(wheelPicker);
    }

    private void obtainProvinceData() {
        for (Province province : mProvinceList) {
            mProvinceNames.add(province.getName());
        }
        mWheelPickerProvince.setData(mProvinceNames);
        setCityAndAreaData(PROVINCE_INITIAL_INDEX);
    }

    private void addListenerToWheelPicker() {
        // 监听省份的滑轮,根据省份的滑轮滑动的数据来设置市跟地区的滑轮数据
        mWheelPickerProvince.setOnItemSelectedListener((picker, data, position) -> {
            // 获得该省所有城市的集合
            mCityList = mProvinceList.get(position).getCity();
            setCityAndAreaData(position);
        });

        mWheelPickerCity.setOnItemSelectedListener((picker, data, position) -> {
            // 获取城市对应的城区的名字
            mWheelPickerArea.setData(mCityList.get(position).getArea());
        });
    }

    private void setCityAndAreaData(int position) {
        // 获得该省所有城市的集合
        mCityList = mProvinceList.get(position).getCity();
        // 获取所有city的名字
        // 重置先前的城市集合数据
        mCityNames.clear();
        for (City city : mCityList) {
            mCityNames.add(city.getName());
        }
        mWheelPickerCity.setData(mCityNames);
        mWheelPickerCity.setSelectedItemPosition(0);
        // 获取第一个城市对应的城区的名字
        // 重置先前的城区集合的数据
        mWheelPickerArea.setData(mCityList.get(0).getArea());
        mWheelPickerArea.setSelectedItemPosition(0);
    }

    @Override
    public String getProvince() {
        return mProvinceList.get(mWheelPickerProvince.getCurrentItemPosition()).getName();
    }

    @Override
    public String getCity() {
        return mCityList.get(mWheelPickerCity.getCurrentItemPosition()).getName();
    }

    @Override
    public String getArea() {
        return mCityList.get(mWheelPickerCity.getCurrentItemPosition())
            .getArea()
            .get(mWheelPickerArea.getCurrentItemPosition());
    }

    @Override
    public void hideArea() {
        removeComponentAt(INT_2);
    }

    private int dip2px(Context context, float dpValue) {
        return AttrHelper.vp2px(dpValue, context);
    }
}
